﻿using System;
using System.Web.Routing;
using ReadyApps.Common;
using ReadyApps.Common.Exceptions;

namespace ReadyApps.Models.Wiki
{
    class WikiUrlManager :IWikiUrlManager
    {
        #region Variables

        private RouteCollection routes;
        private string baseFolder;

        #endregion

        #region Constructor

        public WikiUrlManager(string baseFolder, RouteBase route)
        {
            if (string.IsNullOrEmpty(baseFolder))
            {
                throw new ArgumentNullException("baseFolder");
            }
            if (route == null)
            {
                throw new ArgumentNullException("route");
            }
            routes = new RouteCollection();
            routes.Add(route);
            this.baseFolder = baseFolder;
        }

        #endregion

        #region Public Methods

        public string GetVirtualUrl(string fullPath)
        {
            if (fullPath.Length < baseFolder.Length)
            {
                throw new UnreachableFolderException(baseFolder, fullPath);
            }
            string workingPath = fullPath.Substring(0, baseFolder.Length);
            if (baseFolder.ToUpper() == workingPath.ToUpper())
            {
                workingPath = fullPath.Substring(baseFolder.Length);
            }
            else
            {
                throw new ArgumentException("The full path must be within the same folder hierarchy as the base folder.", "fullPath");
            }
            return routes.GetVirtualPath(null, new RouteValueDictionary { { Application.PATH_DATA_KEY, workingPath } }).VirtualPath;
        }

        #endregion
    }
}
